<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>用户注册表单验证</title>
</head>

<body>
  <form id="registerForm">
    <label for="username">用户名：</label>
    <input type="text" id="username" required minlength="3" placeholder="请输入至少3个字符的用户名">
    <br><br>
    <label for="email">邮箱：</label>
    <input type="email" id="email" required pattern="^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$"
      placeholder="请输入有效的邮箱">
    <br><br>
    <label for="password">密码：</label>
    <input type="password" id="password" required minlength="6" placeholder="请输入至少6个字符的密码">
    <br><br>
    <input type="submit" value="注册">
  </form>
  <script>
    const registerForm = document.getElementById('registerForm');
    registerForm.addEventListener('submit', function (e) {
      const username = document.getElementById('username').value;
      const email = document.getElementById('email').value;
      const password = document.getElementById('password').value;

      const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;

      if (!emailRegex.test(email)) {
        alert('请输入有效的邮箱');
        e.preventDefault();
      }

      if (username.length < 3) {
        alert('用户名必须至少3个字符');
        e.preventDefault();
      }

      if (password.length < 6) {
        alert('密码必须至少6个字符');
        e.preventDefault();
      }
    });
  </script>
</body>

</html>